//
//  SearchViewController.m
//  Youhuiju
//
//  Created by 余尚飞 on 16/8/2.
//  Copyright © 2016年 yutenys. All rights reserved.
//

#import "SearchViewController.h"

//跳转界面
#import "GoodsDetailViewController.h"
#import "SearchDetailViewController.h"


//自定义视图
#import "SearchTopView.h"
#import "AllBtnClickedView.h"

//自定义cell
#import "SearchCollectionViewCell.h"
@interface SearchViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,clickedCellTitleDelegate,keyBoardClickedDelegate>

@property(nonatomic,strong)SearchTopView *topView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property(nonatomic,strong)AllBtnClickedView *clickedView;

@property(nonatomic,assign)CGFloat cellX ; //cell的初始x
@property(nonatomic,assign)CGFloat cellY ;//cell的初始y
@property(nonatomic,assign)CGFloat cellVGap ;//cell的竖直间距
@property(nonatomic,assign)CGFloat cellWidth;//cell的宽度
@property(nonatomic,assign)CGFloat cellHGap ;//cell横向间距


@property(nonatomic,strong)NSString *searchText;//搜索字段

//占位数据
@property (strong, nonatomic)NSArray *dataArray;
@property(nonatomic,strong)    NSMutableArray *cellArray;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *collectionViewBottom;

@end
@implementation SearchViewController



static NSString *SearchCollectionViewCellIden = @"SearchCollectionViewCellIden";


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.collectionViewBottom.constant = 450 * FitH;
    
    [self load_UI];
    
    
    
    
    
    // Do any additional setup after loading the view from its nib.
}

#pragma mark ------- load_UI
-(void)load_UI
{

    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
  _cellX = 12 * FitW; //cell的初始x
    _cellY = 5 * FitH;//cell的初始y
    _cellVGap = 10 * FitH;//cell的竖直间距
//   _cellWidth;//cell的宽度
 _cellHGap = 10 * FitW;//cell横向间距
    
    
    self.dataArray = @[@"智利进口帝王蟹",@"澳洲谷饲牛脊骨肉骨段",@"美迪惠面膜",@"AHC面膜",@"智利进口帝王蟹",@"澳洲谷饲牛脊骨肉骨段",@"美迪惠面膜",@"智利进口帝王蟹",@"AHC面膜"];
    
    _cellArray = [NSMutableArray array];

    
    [self topView];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource  = self;
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"SearchCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:SearchCollectionViewCellIden];
    
    
    
}


#pragma mark ------ collectionView delegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:SearchCollectionViewCellIden forIndexPath:indexPath];
    [_cellArray addObject:cell];
    
    cell.titleLabel.text = self.dataArray[indexPath.row];
    cell.dataString = self.dataArray[indexPath.row];
    cell.backgroundColor = [UIColor whiteColor];
//    if (indexPath.row) {
//        UICollectionViewCell *preCell = _cellArray[indexPath.row - 1];
////        DLog(@"%@------%ld",preCell,indexPath.row);
//        if (cell.frame.origin.x > 10 * FitW) {
//            if (cell.frame.origin.x + cell.frame.size.width > self.view.frame.size.width - 0 * FitW )
//            {
//                cell.frame = CGRectMake(10 * FitW, cell.frame.origin.y + cell.frame.size.height, cell.frame.size.width, cell.frame.size.height);
//            }
//            else
//            {
//                cell.frame = CGRectMake(preCell.frame.origin.x + preCell.frame.size.width + 10 * FitW, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
//            }
//        }
//    }
    _cellWidth = [self WidthWithString:self.dataArray[indexPath.row] fontSize:14 * FitH height:30 * FitH];
    
    if (indexPath.row < self.dataArray.count)
    {
        
        if (_cellX + _cellWidth > 375 * FitW - 24 * FitW)
        {
            _cellX = 12 * FitW;
            _cellY = _cellVGap + 30 * FitH + _cellY;
        }
        cell.frame = CGRectMake(_cellX, _cellY, _cellWidth, 30 * FitH);
        _cellX = _cellX + _cellWidth + _cellHGap;
    }
    
    return cell;

}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *attrs = @{NSFontAttributeName:[UIFont systemFontOfSize:13 * FitH]};
    CGFloat cellWidth = [self.dataArray[indexPath.row] boundingRectWithSize:CGSizeMake(0, 30 * FitH) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrs context:nil].size.width;
    
    
    return CGSizeMake(cellWidth * FitW, 30 * FitH);
}

//-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
//{
//    return UIEdgeInsetsMake(0 * FitH, 13 * FitW, 0, 0 * FitW);
//}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    GoodsDetailViewController *DVC = [[GoodsDetailViewController alloc]initWithNibName:@"GoodsDetailViewController" bundle:nil];
    self.hidesBottomBarWhenPushed = YES;
    
    [self.topView.mySearchBar resignFirstResponder];//回收键盘
    [self.navigationController pushViewController:DVC animated:YES];
//    self.hidesBottomBarWhenPushed = NO;
}

//回收键盘
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.topView.mySearchBar resignFirstResponder];
    
    self.clickedView.hidden = YES;
}



#pragma mark ------- private delegate
//顶部搜索框“全部”按钮点击代理事件
-(void)clickedCellChangeTitle:(NSString *)titleString
{
    [self.topView.mySearchBar resignFirstResponder];
    [self.topView.mySearchBar.allButton setHighlighted:NO];
    self.topView.mySearchBar.allButton.titleLabel.text = titleString;
    [_topView.mySearchBar.allButton setTitle:titleString forState:UIControlStateNormal];
    NSInteger length                                   = titleString.length;
    CGRect rx                                          = CGRectMake( 0,0,(30 + length * 15 ) * FitW, 30 * FitH);
    _topView.mySearchBar.intputView.frame              = rx;
    _topView.mySearchBar.leftView                      = _topView.mySearchBar.intputView;
    [self.topView.mySearchBar becomeFirstResponder];
}


-(CGFloat)WidthWithString:(NSString *)string fontSize:(CGFloat)fontSize height:(CGFloat)height;
{
    NSDictionary *attrs = @{NSFontAttributeName:[UIFont systemFontOfSize:14]};
    return  [string boundingRectWithSize:CGSizeMake(0, 30) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrs context:nil].size.width * FitW;
}

//键盘搜索键点击代理事件
-(void)clickedAction:(NSString *)searchText
{
    self.searchText = searchText;
    DLog(@"点击键盘搜索键代理事件----------%@",searchText);
    //判断输入框是否为空或者空格键
     NSString *textFieldText = [searchText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if ([textFieldText length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"请输入您想搜索的关键字哦" delegate:self cancelButtonTitle:@"知道啦" otherButtonTitles:nil, nil];
        [alert show];
    }
    else
    {
        [self.topView.mySearchBar resignFirstResponder];
        SearchDetailViewController *svc = [[SearchDetailViewController alloc]initWithNibName:@"SearchDetailViewController" bundle:nil];
        svc.searchText = self.searchText;
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:svc animated:YES];
    }
}


//页面消失时回收键盘
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    [self.topView.mySearchBar becomeFirstResponder];
}








#pragma mark -------- lazy loading
-(SearchTopView *)topView
{
    WeakObj(self);
    if (!_topView)
    {
        _topView = [[SearchTopView alloc]init];
//        _topView.mySearchBar.isFirstResponder = YES;
//        _topView.backgroundColor = [UIColor redColor];
        _topView.mySearchBar.keyBoardDelegate = self;
        [self.view addSubview:_topView];
        [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.top.equalTo(self.view.mas_top).offset(20);
            make.height.mas_offset(44);
        }];
        
        _topView.backButtonClickedHandler = ^(NSInteger buttonTag){
        
            if (buttonTag == 0)
            {
                [weakself.topView.mySearchBar resignFirstResponder];//回收键盘

                [weakself.navigationController popViewControllerAnimated:YES];
            }
            else if(buttonTag == 1)
            {
                DLog(@"搜索一下~~~~~~~~");
                [weakself.topView.mySearchBar resignFirstResponder];//回收键盘
//
//                SearchDetailViewController *svc = [[SearchDetailViewController alloc]initWithNibName:@"SearchDetailViewController" bundle:nil];
//                weakself.hidesBottomBarWhenPushed = YES;
//                [weakself.navigationController pushViewController:svc animated:YES];
            }
            else
            {
                DLog(@"全部~~~~~~~~~~~~~~");
                weakself.clickedView = [AllBtnClickedView getInstance];
                weakself.clickedView.layer.cornerRadius = 5 * FitH;
                weakself.clickedView.backgroundColor = [UIColor blackColor];
                weakself.clickedView.alpha = .7;
                weakself.clickedView.clikedCellDelegate = weakself;
                [weakself.view addSubview:weakself.clickedView];
                [weakself.clickedView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(weakself.topView.mas_bottom).offset(5 * FitH);
                    make.left.equalTo(weakself.view.mas_left).offset(28 * FitW);
                    make.size.mas_offset(CGSizeMake(92 * FitW, 144 * FitH));
                }];
                weakself.clickedView.hidden = NO;
                
            }
        };
        
    }
    return _topView;
}



@end
